package com.larry.spark.rdd.transform

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

object RDD_Oper_aggregateByKey {

  def main(args: Array[String]): Unit = {
    //TODO  使用spark aggregateByKey

    val conf = new SparkConf().setMaster("local[*]").setAppName("rdd")
    val sc = new SparkContext(conf)

    val rdd = sc.makeRDD(
      List(
        ("a",1),("a",2),("c",3),
        ("b",4),("c",5),("c",6)
      ),2
    )
    //
    val rdd1 = rdd.aggregateByKey(0)( //初始值
      (x, y) => { //分区内
        math.max(x, y)
      },
      (x, y) => { //分区间
        x + y
      }
    )

    //wordcount
    val rdd2 = rdd.aggregateByKey(0)( //初始值
      (x, y) => { //分区内
        x + y
      },
      (x, y) => { //分区间
        x + y
      }
    )

    val rdd3 = rdd.aggregateByKey(0)(_+_,_+_)

    //如果分区内和分区外的规则一样 可以使用foldByKey代替
    val rdd4 = rdd.foldByKey(0)(_+_)

    rdd4.collect().foreach(println)
 
    sc.stop()
  }
}
